package com.bfly.mall.user.controller;

import com.bfly.common.ResponseUtil;
import com.bfly.common.page.Pager;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.context.PagerThreadLocal;
import com.bfly.mall.user.entity.Address;
import com.bfly.mall.user.dto.AddressListDTO;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.mall.user.entity.User;
import com.bfly.mall.user.service.IAddressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户收货地址
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/9/18 21:08
 */
@RestController
@RequestMapping(value = "/manage/address")
public class AddressController extends BaseController {

    @Autowired
    private IAddressService addressService;


    /**
     * 收货地址列表
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/18 21:10
     */
    @GetMapping(value = "/list")
    public void list(HttpServletResponse response, HttpServletRequest request) {
        PagerThreadLocal.set(request);
        String consignee = request.getParameter("consignee");
        Map<String, String> unExactQuery = new HashMap<>(2);
        if (StringUtils.isNotBlank(consignee)) {
            unExactQuery.put("consignee", consignee);
        }
        Pager<Address> pager = addressService.getPage(null, unExactQuery, null);
        Pager<AddressListDTO> dtoPager = new Pager<>(pager.getPageNo(), pager.getPageSize(), pager.getTotalCount());

        if (pager.getData() != null) {
            List<AddressListDTO> list = new ArrayList<>();
            User user;
            for (Address address : pager.getData()) {
                AddressListDTO dto = new AddressListDTO();
                BeanUtils.copyProperties(address, dto);

                user = address.getUser();
                if (address.getUser() != null) {
                    dto.setNickName(user.getNickName());
                }
                list.add(dto);
            }
            dtoPager.setData(list);
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(dtoPager));
    }
}